<?php


include_once (BASE_PATH.'/includes/cz88/start.php');
use think\IpLocation;

define('AES_KEY', 'aabbcc+575732022'); // 自定义密钥
define('AES_IV', 'aaa9911887xlsdev'); // 固定 IV，确保长度为 16 字节
define('COOKIE_OVERDUE_DAY', 15); // COOKIE过期时间

function aesEncrypt($plaintext) {
    $ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', AES_KEY, 0, AES_IV);
    return base64_encode($ciphertext);
}

function aesDecrypt($ciphertext) {
    return openssl_decrypt(base64_decode($ciphertext), 'aes-256-cbc', AES_KEY, 0, AES_IV);
}

function md5password($pwd){
    $aespwd = aesEncrypt($pwd);
    return strrev(md5($aespwd."xls"));
}

function isValidPhoneNumber($phone) {
    $pattern = '/^1[3-9]\d{9}$/';
    return preg_match($pattern, $phone) === 1;
}

function generateUserId($phone) {
    $timestamp = round(microtime(true) * 1000);     // 毫秒级时间戳
    $userId = substr(md5($phone.$timestamp.generateRandomString(5)), 0, 24);

    return $userId;
}

function generateCommentsId($uid,$nid) {
    $timestamp = round(microtime(true) * 1000);     // 毫秒级时间戳
    $CommentsId = substr(strrev(md5($uid.$nid.$timestamp.generateRandomString(6))), 0, 24);

    return $CommentsId;
}

function generateNoteId($uid) {
    $timestamp = round(microtime(true) * 1000); // 毫秒级时间戳
    // 生成 NoteId
    $noteIdBase = md5(md5($uid . $timestamp . generateRandomString(6) . generateRandomString(6)));

    $isReverse = rand(0, 1);
    $finalNoteId = $isReverse ? strrev($noteIdBase) : $noteIdBase;

    return substr($finalNoteId, 0, 24);
}

function generatePicId() {
    $timestamp = round(microtime(true) * 1000);
    $randomString = bin2hex(random_bytes(10));
    $uniqueId = md5($timestamp . $randomString);

    return substr($uniqueId, 0, 24);
}

function getUserIp() {
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    // 多IP取第一
    if (strpos($ip, ',') !== false) {
        $ip = explode(',', $ip)[0];
    }

    return $ip;
}

function getUserIPApi1()
{
    $result = curlRequest("https://searchplugin.csdn.net/api/v1/ip/get");
    if ($result['success']) {
        $ip = json_decode($result['response'],true)["data"]["ip"];
        return $ip;
    } else {
        return "127.0.0.1";
    }
}

function getUserIpApi2()
{
    $result = curlRequest("https://www.ipplus360.com/getIP");
    if ($result['success']) {
        $ip = json_decode($result['response'],true)["data"];
        return $ip;
    } else {
        return "127.0.0.1";
    }
}


function getIpProvince($ip)
{
    if (is_numeric($ip)) {
        $ip = long2ip($ip);
    }
    return IpLocation::getLocation($ip)["province"];
}

function getUserIpAsLong() {
    $ip = getUserIpApi2();
    return ip2long($ip);
}

function generateNickname() {
    return '小蓝鼠_' . generateRandomString(5);
}

function random_chinese_ip() {
    // 常用的中国 IP 范围
    $ip_ranges = [
        ['61.172.0.0', '61.175.255.255'],
        ['112.116.0.0', '112.117.255.255'],
        ['111.126.0.0', '111.127.255.255'],
        ['117.121.128.0', '117.121.191.255'],
        ['114.111.0.0', '114.111.31.255'],
        ['124.161.0.0', '124.161.255.255'],
        ['60.28.0.0', '60.29.255.255'],
        ['103.22.64.0', '103.22.67.255'],
        ['112.122.0.0', '112.123.255.255'],
        ['123.232.0.0', '123.235.255.255'],
        ['183.184.0.0', '183.191.255.255'],
        ['42.62.160.0', '42.62.175.255'],
        ['171.104.0.0', '171.111.255.255'],
        ['49.112.0.0', '49.119.255.255'],
        ['121.224.0.0', '121.239.255.255'],
        ['171.34.0.0', '171.35.255.255'],
        ['121.16.0.0', '121.23.255.255'],
        ['222.85.0.0', '222.85.127.255'],
        ['211.140.0.0', '211.141.255.255'],
        ['103.22.48.0', '103.22.51.255'],
        ['221.232.0.0', '221.235.255.255'],
        ['59.51.0.0', '59.51.127.255'],
        ['202.100.64.0', '202.100.71.255'],
        ['203.16.27.0', '203.16.27.255'],
        ['202.98.224.0', '202.98.231.255'],
        ['103.3.152.0', '103.3.155.255'],
        ['123.177.0.0', '123.177.255.255'],
        ['103.3.148.0', '103.3.151.255'],
        ['103.22.36.0', '103.22.39.255'],
        ['103.22.100.0', '103.22.103.255'],
        ['202.131.48.0', '202.131.63.255'],
        ['103.29.128.0', '103.29.131.255']
    ];

    // 随机选择一个IP段
    $range = $ip_ranges[array_rand($ip_ranges)];

    // 将IP地址转换为整数
    $start_ip = $range[0];
    $end_ip = $range[1];
    $start = sprintf('%u', ip2long($start_ip));
    $end = sprintf('%u', ip2long($end_ip));

    // 在范围内生成一个随机整数，并转换为IP地址
    $random_ip_int = rand($start, $end);
    return $random_ip_int;
}

function generateRandomString($length = 5) {
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $randomString = '';

    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    return $randomString;
}


function generateBlueId()
{
    // 生成第一个数字，避免前导0
    $blueId = random_int(1, 9); // 第一个数字从 1-9 生成，确保不是0

    // 生成剩余的9位数字
    for ($i = 0; $i < 9; $i++) {
        $blueId .= random_int(0, 9); // 追加0-9的随机数字
    }

    return $blueId;
}

function generateCookies($uid,$phone)
{
    $timestamp = round(microtime(true) * 1000);     // 毫秒级时间戳

    // 获取今天的日期并加上15天
    $timestamp_plus_15_days = time() + (COOKIE_OVERDUE_DAY * 86400); // 86400 是一天的秒数

    $cookies = $uid.'_'.$phone.'_'.$timestamp_plus_15_days.'_'.$timestamp.generateRandomString();
    return aesEncrypt($cookies);
}

function isUid($uid) {
    return preg_match('/^[a-zA-Z0-9]+$/', $uid) === 1; // 如果匹配，返回 true，否则返回 false
}

function getFirstValidImage($imageField) {
    $images = explode(',', $imageField);
    // 匹配常见图片格式：.jpg, .jpeg, .png, .gif, .bmp, .webp
    foreach ($images as $image) {
        if (preg_match('/\.(jpg|jpeg|png|gif|bmp|webp)$/i', $image)) {
            // 检测路径是否以斜杠 / 开头
            if (strpos($image, '/') !== 0) {
                $image = '/' . $image; // 如果没有 /，则添加
            }
            return $image; // 返回第一个找到的有效图片格式
        }
    }
    return '/data/img/default.jpg'; // 如果没有找到，返回默认图片地址
}

function getMp4Files($files) {
    // 用于存储 .mp4 文件的数组
    $mp4Files = array();

    // 遍历文件数组
    foreach ($files as $file) {
        // 检查文件扩展名
        if (pathinfo($file, PATHINFO_EXTENSION) === 'mp4') {
            $mp4Files[] = $file; // 将 .mp4 文件添加到新数组
        }
    }

    return $mp4Files[0]; // 返回找到的 .mp4 文件数组
}

function formatNoteTime($note_time) {
    // 将时间戳转换为秒
    $noteTimestamp = (int)$note_time;

    // 获取当前时间的时间戳
    $currentTimestamp = time();

    // 计算时间差
    $timeDiff = $currentTimestamp - $noteTimestamp;

    // 计算天数、小时数和分钟数
    $days = floor($timeDiff / (60 * 60 * 24));
    $hours = floor(($timeDiff % (60 * 60 * 24)) / (60 * 60));
    $minutes = floor(($timeDiff % (60 * 60)) / 60);

    // 根据时间差返回格式
    if ($days > 365) {
        return date('Y-m-d', $noteTimestamp); // 超过一年
    } elseif ($days > 5) {
        return date('m-d', $noteTimestamp); // 超过5天
    } elseif ($days > 0) {
        return "{$days}天前";
    } elseif ($hours > 0) {
        return "{$hours}小时前";
    } elseif ($minutes > 0) {
        return "{$minutes}分钟前"; // 小于一小时
    } else {
        return "刚刚"; // 小于一分钟
    }
}
function formatTimestampToDate($timestamp, $format = 'Y-m-d H:i:s') {
    return date($format, $timestamp);
}

function daddslashes($string) {
    if(is_array($string)) {
        foreach($string as $key => $val) {
            $string[$key] = daddslashes($val);
        }
    } else {
        $string = addslashes($string);
    }
    return $string;
}

function curlRequest($url, $method = 'GET', $data = [], $headers = []) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 直接传递 JSON 字符串
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // 如果有请求头则设置
    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        curl_close($ch);
        return ['success' => false, 'error' => $error_msg];
    }
    curl_close($ch);
    return ['success' => true, 'response' => $response];
}

